/**
 * <p>Copyright: Copyright (c) 2014</p>
 * <p>Company: 联动优势电子商务有限公司</p>
 * <p>2017/5/22</p>
 * @author xtdhwl
 * @description
 * @version 1.0
 * modified:
 */


class CacheDataUtil {

    /**
     * 初始化key
     * @param key
     * @param data
     * @param complete
     */
    init(key, data, complete) {
        var self = this;
        wx.getStorage({
            key: key,
            success: function (res) {
                self._doComplete(key, res, data);
                if (complete) {
                    complete();
                }
            },

            fail: function () {
                self._doComplete(key, null, data);
                if (complete) {
                    complete();
                }
            }
        });
    }

    /**
     * 删除
     * @param key
     */
    remove(key){
        wx.removeStorage({
            key: key
        });
    }

    _doComplete(key, res, data) {
        // UmfLog.log("CacheDataUtil getStorage res:" );
        // UmfLog.log(res);
        if (res && res.data) {
            this._copyValue(res.data, data);
        }
        var self = this;
        this._proxyValue(data, ()=>{
            self._saveStorage(key, data);
        });
    }

    _copyValue(data1, data2) {
        for (var key in data1) {
            data2[key] = data1[key];
        }
    }

    _proxyValue(data, callback) {
        Object.keys(data).forEach(function (prop) {
            // UmfLog.log("_proxyValue key:" + prop);
            var val = data[prop];
            Object.defineProperty(data, prop, {
                get: function () {
                    return val;
                },
                set: function (newVal) {
                    val = newVal;
                    if(callback){
                        callback();
                    }
                }
            });
        });
    }

    _saveStorage(key, data) {
        // UmfLog.log("_saveStorage key:" + key);
        // UmfLog.log(data);
        wx.setStorage({
            key: key,
            data: data
        });
    }
}

module.exports = CacheDataUtil;